//
//  TJSettingMoneyPasswordController.m
//  Teleport
//
//  Created by xtjun on 2020/6/13.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJSettingMailController.h"

@interface TJSettingMailController ()

@property (weak, nonatomic) UITextField *SMSTextField;
@property (weak, nonatomic) UITextField *passwordTextField;
@property (weak, nonatomic) UIButton *saveButton;
@property (weak, nonatomic) UILabel *resendLabel;

@end

@implementation TJSettingMailController {
    dispatch_source_t _sendSMSTimer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor_Hex(0xf2f2f2);
    
    self.navigationBar.title = @"绑定邮箱".localizedString;
    
    UILabel *nameLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor.blackColor title:@"请输入邮箱".localizedString textAlignment:NSTextAlignmentLeft];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.offset(KNavBarHight + 30);
        make.height.offset(40);
    }];
    
    QMUITextField *SMSTextField = [[QMUITextField alloc] init];
    SMSTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 100);
    [SMSTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [SMSTextField shearRoundedCornersWithRadiu:3];
    SMSTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    SMSTextField.backgroundColor = UIColor.whiteColor;
//    SMSTextField.text = @"1147423945@qq.com";
    [self.view addSubview:SMSTextField];
    [SMSTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.right.offset(-16);
        make.top.equalTo(nameLabel.mas_bottom);
        make.height.offset(40);
    }];
    
    
    UILabel *resendLabel = [UILabel lableWithSuperView:SMSTextField font:UIFont_Px(14) color:UIColor_Hex(0x3881E8) title:@"发送".localizedString textAlignment:NSTextAlignmentCenter];
    [resendLabel addTapGesturesWithTarget:self action:@selector(tapResendLabel)];
    [resendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.centerY.offset(0);
        make.width.offset(60);
        make.height.offset(30);
    }];
    
    UILabel *bankNumberLabel = [UILabel lableWithSuperView:self.view font:UIFont_Px(14) color:UIColor.blackColor title:@"请输入邮箱验证码".localizedString textAlignment:NSTextAlignmentLeft];
    [bankNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.top.equalTo(SMSTextField.mas_bottom);
        make.height.offset(40);
    }];
    
    QMUITextField *passwordTextField = [[QMUITextField alloc] init];
    [passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    passwordTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [passwordTextField shearRoundedCornersWithRadiu:3];
    passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    passwordTextField.backgroundColor = UIColor.whiteColor;
    passwordTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:passwordTextField];
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLabel);
        make.right.offset(-16);
        make.top.equalTo(bankNumberLabel.mas_bottom);
        make.height.offset(40);
    }];
    
    
    UIButton *saveButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"保存".localizedString];
    saveButton.backgroundColor = UIColor.tj_mainColor;
    [saveButton shearRoundedCornersWithRadiu:22];
    [saveButton addTarget:self action:@selector(didClickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-34);
        make.left.offset(34);
        make.height.offset(44);
        make.centerX.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin - 64);
    }];
    
    
    _SMSTextField = SMSTextField;
    _passwordTextField = passwordTextField;
 
    _SMSTextField.font = UIFont_Px(15);
    _passwordTextField.font = UIFont_Px(15);
    _resendLabel = resendLabel;
    _saveButton = saveButton;
     [self setSMSCodeEnable:NO];
    
    [self textFieldDidChange: _SMSTextField];
}

- (void)tapResendLabel {
    
    
    [self.view endEditing:YES];
    
    
    
    NSMutableDictionary *parameters = @{}.mutableCopy;
    [parameters setObject:_SMSTextField.text forKey:@"mailbox"];
 
    [parameters setObject:@"SETPHMAIL" forKey:@"type"];
    
    
    [TJNetworking.shareNetworking POSTNew:@"data/sms/sendMail" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
       
        [TJHud showAutoHideMessage:@"发送成功".localizedString];
        //开始倒计时
        [self startCountdown];
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

- (void)startCountdown {
    
    [self setSMSCodeEnable:NO];
    
    __block NSInteger timestamp = 120;
    
    dispatch_source_t sendSMSTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(sendSMSTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(sendSMSTimer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(sendSMSTimer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                self.resendLabel.text = @"重新发送".localizedString;
                [self setSMSCodeEnable:YES];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.resendLabel.text = [NSString stringWithFormat:@"%lds", timestamp];
                [self setSMSCodeEnable:NO];
            });
        }
    });
    _sendSMSTimer = sendSMSTimer;
    dispatch_resume(sendSMSTimer);
}


- (void)setSMSCodeEnable:(BOOL)SMSCodeEnable {
    
    if (SMSCodeEnable) {
        _resendLabel.userInteractionEnabled = YES;
        _resendLabel.textColor = UIColor_Hex(0x3881E8);
    } else {
        _resendLabel.userInteractionEnabled = NO;
        _resendLabel.textColor = UIColor_Hex(0x999999);
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    if ( _SMSTextField.text.replacingEmptyString.length) {
          [self setSMSCodeEnable:YES];
    }
    _saveButton.userInteractionEnabled = _SMSTextField.text.replacingEmptyString.length && _passwordTextField.text.replacingEmptyString.length;
    _saveButton.backgroundColor = (_saveButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
}


- (void)didClickSaveButton {
    
    
    
    NSDictionary *parameters = @{
        @"code": _passwordTextField.text,
        @"userId": TJUserInfo.readInfo.userId,
         @"phMail": _SMSTextField.text,
        @"regType":@"MAIL"
    };
    
    [self showloading];
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"member/member/setPhMail" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        [weakself hiddenloading];
        if (weakself.complete) {
            weakself.complete(weakself.SMSTextField.text);
        }
        
        [TJHud showAutoHideMessage:@"设置成功".localizedString];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.navigationController popToRootViewControllerAnimated:YES];
        });
        
        
        
    } failure:^(NSError * _Nonnull error) {
        [weakself hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
    
}




@end
